import {
    login,
    // logout,
    getUserInfo,
    getMenuByToken
} from '@/api/user'
import {
    setToken,
    getToken,
    removeToken,
    setRouterByRoles
} from '@/utils/index'
// import routers from '@/router'
import storage from '@/utils/localStorage'
import router, { resetRouter } from '@/router'

const state = {
    userName: window.localStorage.getItem('userName') || '',
    userId: window.localStorage.getItem('userId') || '',
    avatarImgPath: '',
    token: getToken(),
    roles: [],
    hasGetInfo: false,
    menuList: [],
    phone: '',
    rolePlayer: ''
}

const actions = {
    // 登录
    handleLogin ({ state, commit }, { userName, password }) {
        return new Promise((resolve, reject) => {
            try {
                login({
                    userName,
                    password
                }).then(res => {
                    const data = res.data
                    commit('setToken', data.token)
                    resolve(data)
                }).catch(err => {
                    reject(err)
                })
            } catch (error) {
                reject(error)
            }
        })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
        return new Promise((resolve, reject) => {
            // logout(state.token).then(() => {
            //     commit('setToken', '')
            //     commit('setRoles', [])
            //     resolve({
            //         code: '200',
            //         message: '成功'
            //     })
            // }).catch(err => {
            //     reject(err)
            // })
            // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
            commit('setToken', '')
            commit('setRoles', [])
            removeToken()
            window.localStorage.clear()
            resolve({ code: 200, message: '操作成功' })
        })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
        return new Promise((resolve, reject) => {
            try {
                getUserInfo(state.token).then(res => {
                    const data = res.data.result
                    commit('setAvatar', data.avatar)
                    commit('setUserName', data.name)
                    commit('setUserId', data.userId)
                    commit('setRoles', data.roles || [])
                    commit('setPhone', data.phone)
                    resolve(data)
                }).catch(err => {
                    reject(err)
                })
            } catch (error) {
                reject(error)
            }
        })
    },
    // 根据首页路径参数设置token
    setLoginToken ({ state, commit }, { token, userId }) {
        return new Promise((resolve, reject) => {
            if (token) {
                commit('setToken', token)
                commit('setUserId', userId)
                // 获取动态路由
                getMenuByToken({ token, userId }).then(res => {
                    let userData = {}
                    if (res && ((res.data && res.data.success) || (res.result && res.success))) {
                        userData = res.result ? res : res.data
                        if (userData.result && userData.result.menuList) {
                            let menuListData = JSON.parse(userData.result.menuList)
                            let btnListData = JSON.parse(userData.result.btnMap)
                            let { roles } = setRouterByRoles(menuListData, btnListData)
                            commit('setRoles', roles)
                            resolve(roles)
                        } else {
                            commit('setRoles', [])
                            resolve({ roles: [] })
                        }
                        commit('setRolePlayer', decode)
                        commit('setUserName', userData.result.name)
                        commit('setPhone', userData.result.phone)
                    } else {
                        reject(res)
                    }
                }).catch(err => {
                    reject(err)
                })
            } else {
                resolve({
                    data: {
                        success: true
                    }
                })
            }
        })
    },
    // 设置权限路由
    async setMenuList ({ commit, dispatch }, result) {
        let menuListData = JSON.parse(result.menuList)
        let btnListData = JSON.parse(result.btnMap)
        let { roles } = setRouterByRoles(menuListData, btnListData)
        if (roles.length) {
            const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
            accessRoutes.length && commit('setMenuList', accessRoutes)
            commit('setRoles', roles)
        }
        return roles
    },
    // dynamically modify permissions
    changeRoles ({ commit, dispatch }, role) {
        return new Promise(async resolve => {
            const token = role + '-token'

            commit('setToken', token)

            const { roles } = await dispatch('getInfo')

            resetRouter()

            // generate accessible routes map based on roles
            const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

            // dynamically add accessible routes
            router.addRoutes(accessRoutes)

            // reset visited views and cached views
            dispatch('tagsView/delAllViews', null, { root: true })

            resolve()
        })
    },
    // remove token
    resetToken ({ commit }) {
        return new Promise(resolve => {
            commit('setToken', '')
            commit('setUserId', '')
            commit('setRoles', [])
            removeToken()
            resolve()
        })
    }
}

const mutations = {
    setAvatar (state, avatarPath) {
        state.avatarImgPath = avatarPath
    },
    setUserId (state, id) {
        state.userId = id
        if (id) {
            storage.local.setStore('userId', id)
        } else {
            storage.local.del('userId')
        }
    },
    setUserName (state, name) {
        state.userName = name
        storage.local.setStore('userName', name)
    },
    setRoles (state, roles) {
        state.roles = roles
        // storage.local.setStore('roles', roles)
    },
    setToken (state, token) {
        state.token = token
        setToken(token)
    },
    setMenuList (state, menuList) {
        state.menuList = menuList || []
    },
    setPhone (state, phone) {
        state.phone = phone || []
    },
    setRolePlayer (state, rolePlayer) {
        state.rolePlayer = rolePlayer || []
    }
}

export default {
    namespaced: true, // 用于在全局引用此文里的方法时标识这一个的文件名
    state,
    mutations,
    getters: {
        userInfo: state => ({
            userName: state.userName,
            userId: state.userId,
            avatarImgPath: state.avatarImgPath,
            roles: state.roles,
            phone: state.phone,
            rolePlayer: state.rolePlayer
        }),
        roles: state => state.roles
    },
    actions
}
